<template>
	<view class="commentsPage bg-fff">
		<view class="faqs">
            <view class="questionContent">
                <view class="faqItem flex">
                	<view class="faqTitle">
                		<image class="userImg" :src="questionInfo.user_image" mode="aspectFill" v-if="questionInfo.user_image"/>
                        <u-icon name="account-fill" color="#A3A8CF" size="24" v-else></u-icon>
                	</view>
                	<view class="cmTxt left-10">
                		<view class="userNameDate flex">
                            <text class="font14 txtHidden right-5">{{questionInfo.user_nick}}</text>
                		</view>
                		<text class="commonTxt font13 top-5">{{questionInfo.content}}</text>
                	</view>
                </view>
                <view class="questionTimeBox flex top-15">
                    <text class="time font12 col-grey">{{dateFormat(questionInfo.create_time)}}</text>
                    <view class="viewsBtns flex font13">
                        <block v-if="questionInfo.review === 0">
                            <view class="flex" @click="clickThumb(questionInfo)">
                                <u-icon :name="questionInfo.love?'thumb-up-fill':'thumb-up'" :color="questionInfo.love?'#007235':'#3E3A3A'" size="16"></u-icon><text class="left-3">{{questionInfo.like_num}}</text>
                            </view>
                            <view class="left-15 flex" @click="clickCollect(questionInfo)">
                                <u-icon :name="questionInfo.store?'star-fill':'star'" :color="questionInfo.store?'#007235':'#3E3A3A'" size="16"></u-icon><text class="left-3">{{questionInfo.store_num}}</text>
                            </view>
                            <view class="left-15 flex" @click="toAnsForm">
                                <u-icon name="chat" color="#3E3A3A" size="16"></u-icon><text class="left-3">{{questionInfo.count}}</text>
                            </view>
                        </block>
                        <view class="left-15 flex" v-if="questionInfo.owner" @click="clickDelete('question',questionInfo.id)">
                            <u-icon name="trash" color="#3E3A3A" size="16"></u-icon><text class="left-3">删除</text>
                        </view>
                    </view>
                </view>
            </view>

            <view class="answerContent" v-if="reply_list.length > 0">
                <view class="allAnswerTitle fontBold font16 left-15 top-15">全部回答</view>
                <view class="faqItem border-bottom-gray" v-for="(item,num) in reply_list" :key="num">
                	<view class="anwerUserInfoBox flex">
                		<image class="userImg" :src="item.user_image" mode="aspectFill" />
                        <text class="userName font14 left-10 right-5">{{item.user_nick}}</text>
                	</view>
                    <view class="contentBox top-10">
                        <text class="answerIcon col-fff bg-theme font12 right-5">答</text>
                        <block v-for="(val, valIndex) in item.values" :key="valIndex">
                            <text :class="val.isHot?'isKeyword':''" @click.stop="toSearchHotKeyword(val, item.user)">{{val.text}}<text class="iconSearch bg left-5 right-3"></text></text>
                        </block>
                    </view>
                	<view class="answerDateBox flex top-10">
                        <text class="time font12 col-grey">{{ dateFormat(item.create_time) }}</text>
                        <view class="flex">
                            <button class="authBtn clearBtn flex" @click="clickThumb(item)">
                                <u-icon :name="item.love?'thumb-up-fill':'thumb-up'" :color="item.love?'#007235':'#3E3A3A'" size="16"></u-icon><text class="left-3">{{item.like_num}}</text>
                            </button>
                            <button class="deleteBtn clearBtn flex" v-if="item.owner" @click="clickDelete('answer',item.id, num)">
                                <u-icon name="trash" color="#3E3A3A" size="16"></u-icon><text class="left-3">删除</text>
                            </button>
                        </view>
                	</view>
                </view>
            </view>
            
            <up-empty mode="list" text="暂无回答" marginTop="100" v-if="loadingType == 'nomore' && reply_list.length == 0"></up-empty>
            <up-loadmore :status="loadingType" margin-top="30" v-else />
		</view>
		<view class="bottomBox boxShow flex bg-fff col-fff font15" v-if="questionInfo.review === 0">
            <button class="subNewMsg" @click="toFaqForm">我要提问</button>
            <button class="joinGroup" @click="toAnsForm">我来回答</button>
		</view>
	</view>
</template>
<script>
    import { mapState, mapActions } from 'pinia';
    import { useUserInfoStore, useIndexStore } from '@/store/index';
    import { checkLogin, checkUserInfo, UTCConvertTime } from '@/common/common';
    import { questionDetail, FAQThumbsUp, FAQCollect, deleteOwnerFAQ, adviserLockUser, loadFaqCommentList } from '@/common/api/forum';
	export default {
		data() {
			return {
                firstLoad: true,
				questionId: '',
				next: '',
				loadingType: 'loadmore',
				questionInfo: {},
				reply_list: [],
                scrollAnimate: false
			}
		},
        computed: {
        	...mapState(useUserInfoStore, ['userInfo'])
        },
        onPageScroll() {
            const that = this;
            that.scrollAnimate = true;
            this.$u.debounce(function() {
                that.scrollAnimate = false;
            }, 500);
        },
      
        onShow() {
            if(!this.firstLoad) {
                this.next = '';
                this.loadingType = 'loadmore';
                this.reply_list = [];
                this.init()
            }
        },
		onLoad(options){
            const that = this;
			this.questionId = options.id || '';
            uni.$check_and_login(function() {
                that.init()
            })
		},
		onReachBottom(){
			this.loadData()
		},
		methods: {
            ...mapActions(useIndexStore, ['setUpdateForum']),
            ...mapActions(useUserInfoStore, ['checkUserInfo']),

            dateFormat(val){
                if(!val) return '';
        		return UTCConvertTime(val, '{y}-{m}-{d} {h}:{i}').slice(-11);
            },
            
            //初始化请求
			async init(){
                try {
                    let { status, detail } = await questionDetail(this.questionId);
                    if(status !== 0) {
                        uni.$u.toast(detail);
                        return;
                    }
                    this.questionInfo = detail;
		            await this.checkUserInfo();//验证用户信息,如果没有就获取并且更新
                } catch (error) {}
                this.firstLoad = false;
				await this.loadData();
			},
            
            //加载评论
			async loadData(){
				if(this.loadingType === 'loading' || this.loadingType === 'nomore') return;
				this.loadingType = 'loading';
				let url = this.next || `/product/mall/qa/v2/answer/${this.questionId}`;
                try {
                    let { status, detail } = await loadFaqCommentList(url);
                    if(status !== 0) {
                        uni.$u.toast(detail);
                        return;
                    }
                    this.reply_list = [];
                    this.reply_list = detail.results.map(item => ({
                        ...item,
                        values: [{
                            text: item.content,
                            productId: '',
                            isHot: false
                        }]
                    }));
                    this.next = detail.next;
                    this.loadingType = detail.next ? 'loadmore' : 'nomore';
                } catch (error) {
                    console.log(error)
                }
			},
            
            //搜索关键词
            async toSearchHotKeyword(info, userId) {
                if(!info.isHot) return;
                await adviserLockUser({
                    uid: userId,
                    product_id: info.productId
                });
                uni.navigateTo({
                    url: `/pages/product/detail/index?productId=${info.productId}&title=${info.text}&prepage=问答详情页-${info.productId}-${info.text}`
                })
            },
            
            //点击点赞
            clickThumb(info) {
                if(!checkLogin()) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    return
                }
                if(!checkUserInfo()) {
                    uni.navigateTo({
                        url: `/pages/login/user-info-form`
                    })
                    return
                }
                FAQThumbsUp(info.id).then(res => {
                    this.setUpdateForum(true);
                    info.love?info.like_num--:info.like_num++;
                    info.love = !info.love;
                })
            },
            
            //点击收藏
            clickCollect(info) {
                if(!checkLogin()) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    return
                }
                if(!checkUserInfo()) {
                    uni.navigateTo({
                        url: `/pages/login/user-info-form`
                    })
                    return
                }
                FAQCollect(info.id).then(res => {
                    this.setUpdateForum(true);
                    info.store?info.store_num--:info.store_num++;
                    info.store = !info.store;
                })
            },
            
            //点击删除
            clickDelete(type, id, index=0) {
                const that = this;
                uni.showModal({
                	title: '提示',
                	content: '是否确认删除?',
                	success: function (res) {
                		if (res.confirm) {
                            deleteOwnerFAQ(id).then(res => {
                                if(res.status == 0) {
                                    uni.$u.toast('删除成功');
                                    that.setUpdateForum(true);
                                    if(type == 'question') {
                                        setTimeout(function() {
                                            uni.navigateBack({
                                                delta: 1
                                            })
                                        },1000)
                                    }else {
                                        that.questionInfo.count--;
                                        that.reply_list.splice(index, 1);
                                    }
                                }else {
                                    uni.$u.toast(res.detail);
                                }
                            })
                		}
                	}
                });
            },
			
            //跳转我要提问
			toFaqForm(){
                if(!checkLogin()) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    return
                }
                if(!checkUserInfo()) {
                    uni.navigateTo({
                        url: `/pages/login/user-info-form`
                    })
                    return
                }
                uni.navigateTo({
                	url: `/pages/tools/question/question-form`
                })
			},
            
            //跳转我要回答
			toAnsForm(){
                if(!checkLogin()) {
                    uni.navigateTo({
                        url: '/pages/login/login'
                    })
                    return
                }
                if(!checkUserInfo()) {
                    uni.navigateTo({
                        url: `/pages/login/user-info-form`
                    })
                    return
                }
				uni.navigateTo({
					url: `/pages/tools/question/answer-form?id=${this.questionId}`
				})
			}
		}
	}
</script>

<style scoped lang="scss">
    .border-bottom-gray{
        border-bottom: 2rpx solid rgba(0,0,0,.06);
    }
	.commentsPage{
		padding-bottom: 160rpx;
        min-height: 100vh;
	}
    .authBtn{
        margin: 0;
        font-size: 26rpx;
    }
	.faqs{
        .questionContent{
            padding: 30rpx;
            border-bottom: 2rpx solid rgba(0,0,0,.06);
            .questionTimeBox{
                justify-content: space-between;
                .viewsBtns{
                    justify-content: flex-start;
                }
            }
        }
        .answerContent{
            .faqItem{
                padding: 30rpx;
            }
            .anwerUserInfoBox{
                justify-content: flex-start;
                .userImg{
                	border-radius: 50%;
                	width: 40rpx;
                	height: 40rpx;
                }
            }
            .contentBox{
                line-height: 1.5;
                .answerIcon{
                    line-height: 1;
                    display: inline-block;
                    padding: 6rpx;
                    border-radius: 4rpx;
                }
                .isKeyword{
                    color: $theme-color;
                    .iconSearch{
                        width: 18rpx;
                        height: 18rpx;
                        display: inline-block;
                        vertical-align: top;
                        margin-top: 4rpx;
                        background-image: url("https://image.srea.org.cn/xcx/icon/icon-search-theme.png");
                    }
                }
            }
            .answerDateBox{
                justify-content: space-between;
                .deleteBtn{
                    margin: 0rpx 0rpx 0rpx 30rpx;
                    font-size: 26rpx;
                }
            }
        }
		.faqItem{
            align-items: flex-start;
            &:last-child{
                border: none;
            }
			.faqTitle{
				justify-content: flex-start;
                .userImg{
                	border-radius: 50%;
                	width: 62rpx;
                	height: 62rpx;
                	line-height: 46rpx;
                }
			}
			.cmTxt{
				width: calc(100% - 82rpx);
				.userNameDate{
                    justify-content: flex-start;
                    line-height: 1.4;
				}
				.commonTxt{
					display: block;
				}
			}
		}
	}
	.allAnswerTitle{
		justify-content: flex-start;
	}
	.bottomBox{
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 160rpx;
		justify-content: space-between;
        z-index: 10;
		.subNewMsg{
			background-color: #007235;
		}
		.joinGroup{
			background-color: #bf7c03;
		}
		.subNewMsg,.joinGroup{
			width: 45%;
			height: 74rpx;
			line-height: 74rpx;
            color: #FFFFFF;
		}
	}
</style>
